package com.zwd.cases.utils.ftp2;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description ftp工具类
 * @Author zhengwd
 * @Date 2022/7/21 9:37
 **/
@Slf4j
public class FTPUtils {

    /**
     * 上传单个文件到FTP
     *
     * @param ftpPath        路径
     * @param uploadFileName 文件名
     * @param input          输入流
     * @return
     */
    public static boolean uploadFile(String ftpPath, String uploadFileName, InputStream input) {
        boolean issuccess = false;
        FTPClient ftpClient = null;
        try {
            ftpClient = FtpClient.getFTPConnection();
            // 切换到工作目录
            if (!ftpClient.changeWorkingDirectory(ftpPath)) {
                ftpClient.changeWorkingDirectory("/");
                String[] dirs = ftpPath.split("/");
                for (String dir : dirs) {
                    ftpClient.makeDirectory(dir);
                    ftpClient.changeWorkingDirectory(dir);
                }
            }
            // 工作模式被动
            ftpClient.enterLocalPassiveMode();
            // 文件写入 远程文件名；输入流
            boolean storeFile = ftpClient.storeFile(uploadFileName, input);
            if (!storeFile) {
                return issuccess;
            }
            input.close();
            ftpClient.logout();
            issuccess = true;
            log.info("==============FTP文件上传成功=================");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return issuccess;
    }

    /**
     * 上传OSS文件到FTP服务器
     * @param ftpPath
     * @param uploadFileName
     * @param ossBean
     */
//    public static void uploadFileToFtpFromOss(String ftpPath, String uploadFileName, OssBean ossBean) {
//        OSSClient ossClient = new OSSClient(ossBean.getEndpoint(), ossBean.getAccessKeyId(), ossBean.getAccessKeySecret());
//        // 获取fileid对应的阿里云上的文件对象
//        OSSObject ossObject = ossClient.getObject(ossBean.getBucketName(), ossBean.getFilePath());
//        // 已缓冲的方式从字符输入流中读取文本，缓冲各个字符，从而提供字符、数组和行的高效读取
//        InputStream inputStream = ossObject.getObjectContent();
//        // 上传文件
//        uploadFile(ftpPath, uploadFileName, inputStream);
//    }
}
